package com.example.wechat;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.example.wechat.utils.SecurityUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Random;

public class ForgotPasswordActivity extends AppCompatActivity {
    private EditText etPhone;
    private EditText etVerificationCode;
    private EditText etNewPassword;
    private EditText etConfirmNewPassword;
    private Button btnSendCode;
    private Button btnResetPassword;
    
    private String verificationCode;
    private CountDownTimer countDownTimer;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgot_password);
        
        initViews();
        setupListeners();
    }
    
    private void initViews() {
        etPhone = findViewById(R.id.etPhone);
        etVerificationCode = findViewById(R.id.etVerificationCode);
        etNewPassword = findViewById(R.id.etNewPassword);
        etConfirmNewPassword = findViewById(R.id.etConfirmNewPassword);
        btnSendCode = findViewById(R.id.btnSendCode);
        btnResetPassword = findViewById(R.id.btnResetPassword);
    }
    
    private void setupListeners() {
        btnSendCode.setOnClickListener(v -> sendVerificationCode());
        btnResetPassword.setOnClickListener(v -> resetPassword());
    }
    
    private void sendVerificationCode() {
        String phone = etPhone.getText().toString().trim();
        if (phone.isEmpty()) {
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 生成6位验证码
        verificationCode = String.format("%06d", new Random().nextInt(999999));
        
        // TODO: 调用短信API发送验证码
        Toast.makeText(this, "验证码已发送: " + verificationCode, Toast.LENGTH_SHORT).show();
        
        // 开始倒计时
        startCountDown();
    }
    
    private void startCountDown() {
        btnSendCode.setEnabled(false);
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                btnSendCode.setText(String.format("%ds", millisUntilFinished / 1000));
            }
            
            @Override
            public void onFinish() {
                btnSendCode.setEnabled(true);
                btnSendCode.setText("发送验证码");
            }
        }.start();
    }
    
    private void resetPassword() {
        String phone = etPhone.getText().toString().trim();
        String code = etVerificationCode.getText().toString().trim();
        String newPassword = etNewPassword.getText().toString().trim();
        String confirmPassword = etConfirmNewPassword.getText().toString().trim();
        
        if (phone.isEmpty() || code.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) {
            Toast.makeText(this, "请填写所有信息", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (!code.equals(verificationCode)) {
            Toast.makeText(this, "验证码错误", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (!newPassword.equals(confirmPassword)) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 在后台线程中重置密码
        new Thread(() -> {
            boolean success = updatePassword(phone, newPassword);
            runOnUiThread(() -> {
                if (success) {
                    Toast.makeText(ForgotPasswordActivity.this, "密码重置成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(ForgotPasswordActivity.this, "密码重置失败", Toast.LENGTH_SHORT).show();
                }
            });
        }).start();
    }
    
    private boolean updatePassword(String phone, String newPassword) {
        Connection conn = null;
        PreparedStatement stmt = null;
        
        try {
            conn = MySQLConnection.getConnection();
            if (conn == null) {
                return false;
            }
            
            String hashedPassword = SecurityUtils.hashPassword(newPassword);
            String sql = "UPDATE users SET password = ? WHERE phone = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, hashedPassword);
            stmt.setString(2, phone);
            
            int result = stmt.executeUpdate();
            return result > 0;
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
} 